<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" :placeholder="$t('Please_enter_store_name')"/>
      <el-input v-model="listQuery.address" clearable class="filter-item" style="width: 200px;" :placeholder="$t('请输入详细地址')"/>
      <el-cascader
        :placeholder="$t('请选择区域地址')"
        class="filter-item"
        v-model="listQuery.regionIds"
        :options="countrys"
        @active-item-change="handleItemChange"
        :props="props"
        clearable
        filterable
      ></el-cascader>
      <el-select v-model="listQuery.status" clearable class="filter-item" :placeholder="$t('Please_select')">
        <el-option :value="1" :label="$t('Open_for_business')"/>
        <el-option :value="2" :label="$t('Closed')"/>
        <el-option :value="3" :label="$t('Renovating')"/>
      </el-select>
      <el-button class="filter-item"  plain1 icon="el-icon-search" @click="handleFilter">{{$t('Search')}}</el-button>
      <el-button  v-permission="['GET /admin/p/store_store_add']" class="filter-item"  plain1 icon="el-icon-circle-plus" @click="handleCreate">{{$t('Add')}}</el-button>
<!--      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{$t('Find')}}</el-button>-->
    </div>

    <el-tooltip placement="top" :content="$t('Back_to_top')">
      <to-bottom :visibility-height="50" />
    </el-tooltip>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" max-height="700" stripe
              :header-cell-style="{background:'#eef1f6',color:'#1d242b',top:'5px'}">
      <el-table-column type="index" :index="getIndex" width="50"></el-table-column>

      <el-table-column align="center" :label="$t('Store_name')" min-width="200" prop="name">
        <template slot-scope="scope">
          <span :style="{color:scope.row.color}">{{scope.row.name}} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('税务编码')" min-width="150" prop="name">
        <template slot-scope="scope">
          <span >{{scope.row.taxCode}} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('Store_address')" width="350" prop="streetAddress">
        <template slot="header" slot-scope="{row}">
          <i class="el-icon-location-information"></i>
          {{$t('Store_address')}}
        </template>
        <template slot-scope="scope">
          <i class="el-icon-location-information"></i>
          <span>{{scope.row.streetAddress}}</span>
          <span v-if="scope.row.regions" >
            {{regions(scope.row.regions)}}
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Store_Manager')" prop="shopkeeper"/>

      <el-table-column align="center" :label="$t('Partners')" prop="members">
        <template slot="header" slot-scope="{row}">
          <i class="el-icon-s-custom"></i>
          {{$t('Partners')}}
        </template>
      </el-table-column>

      <el-table-column sortable align="center" :label="$t('Time_added')" width="220" prop="addTime">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.addTime }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="运营时间" width="120">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleOperateTime(scope.row)">运营时间</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center"  :label="$t('Operation_Status')"  prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'warning' ">{{ consStatus[scope.row.status]}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Operate')" width="380" class-name="small-padding fixed-width">
        <template slot="header" slot-scope="{row}">
          {{$t('Operate')}}
          <i class="el-icon-setting"style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/p/store_store_detail']" round size="small" @click="handleUpdate(scope.row)"><i class="el-icon-view"></i>{{$t('Details')}}</el-button>
          <el-button v-permission="['GET /admin/p/store_store_copy']" round type="primary" size="small" @click="handleCopy(scope.row)"><i class="el-icon-copy-document"></i>{{$t('Copy')}}</el-button>
          <el-button v-permission="['GET /admin/p/store_store_delete']" round type="danger"   size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i>{{$t('Delete')}}</el-button>
          <el-button v-permission="['GET /admin/p/store_store_erpbind']" round plain1 size="small" @click="handleErpBind(scope.row)"><i class="el-icon-paperclip"></i>{{$t('Shop_erp_bind')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-tooltip placement="top" :content="$t('Back_to_top')">
      <back-to-top :visibility-height="200" />
    </el-tooltip>

    <el-dialog :visible.sync="erpBindVisible" :title="$t('Shop_erp_bind')">
      <el-form ref="erpBindForm" :model="erpBindForm" :rules="erpBindFormRules" status-icon label-position="left" label-width="150px">
        <el-form-item :label="$t('ERP_customer_code')" prop="erpCode">
          <el-input v-model="erpBindForm.erpCode"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="erpBindVisible = false">{{$t('Cancel')}}</el-button>
        <el-button @click="submitErpBind()" type="primary">{{$t('Confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="operateDialogVisible" title="门店运营时间" width="1200px">
      <el-descriptions class="margin-top"  :column="3" border>
        <el-descriptions-item v-for="o in 7" :key="o" :span="1">
          <template slot="label">
            <el-tag :style="{width:'80px','text-align':'center'}" type="info">{{ weeksTimeMap[o] }}</el-tag>
          </template>
          <span>{{ (weeksTime[o - 1] || []).join(' - ') }}</span>
        </el-descriptions-item>

        <el-descriptions-item v-for="(item, index) in special" :key="index" :span="1">
          <template slot="label">
            <el-tag effect="dark" type="warning">{{ item.specialDate }}</el-tag>
          </template>
          <span>{{ (item.specialTime || []).join(' - ') }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

  </div>
</template>

<script>
  import ElSelectDropdown from 'element-ui/packages/select/src/select-dropdown'
  import { listShop, deleteShop, bindErpCode, shopCopy } from '@/api/shop'
  import BackToTop from '@/components/BackToTop'
  import ToBottom from '@/components/ToBottom'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import { listCountryRegion, listSubRegion } from '@/api/region'
export default {
  name: 'ShopList',
  components: { ElSelectDropdown, BackToTop, Pagination,ToBottom },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        status: undefined,
        name: undefined,
        address: undefined,
        regionIds:undefined,
        sort: 'add_time',
        order: 'desc'
      },
      goodsDetail: '',
      detailDialogVisible: false,
      downloadLoading: false,
      consStatus:['',this.$t('Open_for_business'), this.$t('Closed'), this.$t('Renovating')],
/*      options: [{
        value:'1',
        label: '江苏',
        cities: [{label:'南京',value:2}]
      }, {
        value:'1',
        label: '浙江',
        cities: []
      }],*/
      props: {
        value:'id',
        label: 'nameEn',
        children: 'children',
        checkStrictly: true
      },
      countrys:[],
      erpBindVisible: false,
      erpBindForm: {
        shopId: undefined,
        erpCode: undefined
      },
      erpBindFormRules: {
        erpCode: [
          { required: true, message: this.$t('ERP_customer_code_cannot_be_empty'), trigger: 'blur' }
        ]
      },
      operateDialogVisible: false,
      weeksTimeMap: {
        1: '周一',
        2: '周二',
        3: '周三',
        4: '周四',
        5: '周五',
        6: '周六',
        7: '周日'
      },
      weeksTime: [],
      special: [],
      selectedDate: '',
      showDatepicker: false,
    }
  },
  created() {
    this.getList()
    this.getCountrys()
  },
  methods: {
    regions(arr){
      const nameEn = arr.map(item => item.nameEn)
      const nameCn = arr.map(item => item.nameCn)
      if(Boolean(nameCn[0])){
        return nameCn.join(',')
      }
      return nameEn.join(',')
    },
    getList() {
      this.listLoading = true
      let param = _.clone(this.listQuery);
      if(param.regionIds){
        param.regionId = this.listQuery.regionIds[this.listQuery.regionIds.length-1]
      }
      delete param.regionIds
      listShop(param).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1

      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: '/shop/create' })
    },
    handleUpdate(row) {
      this.$router.push({ path: '/shop/overview', query: { id: row.id }})
    },
    handleCopy (row) {
      let id = row.shopId
      shopCopy(id).then(response => {
        this.$notify.success({
          title: this.$t('Success!'),
          message: '修改成功'
        })


        let newShopId = response.data.data.shopId
        this.$router.push({ path: '/shop/edit', query: { id: newShopId }})
      })
      .catch(response => {
        MessageBox.alert(this.$t('Error') + this.$t(response.data.errmsg), this.$t('Warning'), {
          confirmButtonText: this.$t('Confirm'),
          type: 'error'
        })
      })
    },
    showDetail(detail) {
      this.goodsDetail = detail
      this.detailDialogVisible = true
    },
    handleDelete(row) {
      this.$confirm(this.$t('Confirm_Delete?'), this.$t('Hint'), {
        confirmButtonText: this.$t('Confirm'),
        cancelButtonText: this.$t('Cancel'),
        type: 'warning'
      }).then(() => {
        this.doDelete(row)
      });
    },
    doDelete(row){
      deleteShop(row.shopId).then(response => {
        this.$notify.success({
          title: this.$t('Success!'),
          message: this.$t('Deleted')
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }).catch(response => {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t(response.data.errmsg)
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['门店名称', '门店地址', '门店店长', '成员', '添加时间', '运营状态']
        const filterVal = ['name', 'address', 'shopkeeper', 'members', 'addTime', 'status']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '门店信息')
        this.downloadLoading = false
      })
    },
    handleItemChange(val) {
      let step = val.length
      let query = {
        id: val[val.length-1],
        type: 1
      }
      listSubRegion(query).then(response=>{
        let result = this.findObject(this.countrys, val)
        response.data.data.list.forEach(child=>{
          if(step <= 1){
            result.children.push(this._.defaults(child,{children:[]}))
          }else{
            result.children.push(child)
          }
        })
      })
    },
    getCountrys(){
      listCountryRegion().then(response=>{
        this.countrys = response.data.data.list.map(function(country){
          return _.defaults(country,{children:[]})
        })
      })
    },
    findObject(arr, ids){
      // let result = undefined
      for(let i=0;i<=arr.length-1;i++){
        let obj = arr[i]
        if(ids.length == 1 && obj.id == ids[0]){
          return obj;
        }else if(obj.id == ids[0]){
          ids.shift()
          return this.findObject(obj.children, ids)
        }
      }
/*      arr.forEach(obj=>{
        if(ids.length == 1 && obj.id == ids[0]){

          result = obj;
        }else if(obj.id == ids[0]){
          ids.shift()
          return this.findObject(obj.children, ids)
        }
      })
      return result*/
    },
    handleErpBind(row) {
      this.erpBindVisible = true
      this.erpBindForm.shopId = row.shopId
      this.erpBindForm.erpCode = row.erpCode
    },
    submitErpBind() {
      this.$refs['erpBindForm'].validate(valid => {
        if (valid) {
          bindErpCode(this.erpBindForm).then(response => {
            this.$notify.success({
              title: this.$t('Success!'),
              message: '修改成功'
            })
            this.erpBindVisible = false
            this.getList()
          })
          .catch(response => {
            MessageBox.alert(this.$t('Error') + this.$t(response.data.errmsg), this.$t('Warning'), {
              confirmButtonText: this.$t('Confirm'),
              type: 'error'
            })
          })
        }
      })
    },
    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    },
    handleOperateTime(row) {
      this.weeksTime = row.weeksTime || Array(7).fill(["00:00:00", "00:00:00"]);
      this.special = row.special || [];
      this.operateDialogVisible = true;
    },


  }
}
</script>

<style scoped>

</style>
